package com.chuangshu.chuangshuteam.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chuangshu.chuangshuteam.entity.TeamMember;
import com.chuangshu.chuangshuteam.entity.UserProfile;
import com.chuangshu.chuangshuteam.entity.Users;
import com.chuangshu.chuangshuteam.mapper.TeamMemberMapper;
import com.chuangshu.chuangshuteam.mapper.UsersMapper;
import com.chuangshu.chuangshuteam.service.UsersService;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class UsersServiceImpl extends ServiceImpl<UsersMapper, Users> implements UsersService {

    @Autowired
    private TeamMemberMapper teamMemberMapper;

    // 从配置文件读取微信小程序配置
    @Value("${wechat.miniapp.app-id}")
    private String appId;
    
    @Value("${wechat.miniapp.app-secret}")
    private String appSecret;
    
    @Value("${wechat.miniapp.login-url}")
    private String wxLoginUrl;

    /**
     * 通过code换取openid和session_key
     * @param code 微信小程序登录接口返回的code
     * @return 包含openid和session_key的Map
     */
    private Map<String, String> getOpenIdByCode(String code) {
        try {
            // 构建请求URL
            String urlStr = wxLoginUrl + "?appid=" + appId + "&secret=" + appSecret + "&js_code=" + code + "&grant_type=authorization_code";
        
            // 发送HTTP请求
            URL url = new URL(urlStr);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5000);
            conn.setReadTimeout(5000);
            
            // 读取响应
            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            StringBuilder response = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
            reader.close();
            
            // 解析JSON响应
            ObjectMapper mapper = new ObjectMapper();
            JsonNode rootNode = mapper.readTree(response.toString());
            
            // 检查是否有错误
            if (rootNode.has("errcode")) {
                int errCode = rootNode.get("errcode").asInt();
                String errMsg = rootNode.get("errmsg").asText();
                log.error("微信登录失败: errcode={}, errmsg={}", errCode, errMsg);
                return null;
            }
            
            // 提取openid和session_key
            String openid = rootNode.get("openid").asText();
            String sessionKey = rootNode.get("session_key").asText();
            
            Map<String, String> result = new HashMap<>();
            result.put("openid", openid);
            result.put("session_key", sessionKey);
            
            // 如果用户是UnionID机制用户，会返回unionid
            if (rootNode.has("unionid")) {
                result.put("unionid", rootNode.get("unionid").asText());
            }
            
            return result;
            
        } catch (Exception e) {
            log.error("微信登录请求失败: {}", e.getMessage(), e);
            return null;
        }
    }

    /**
     * 微信登录或注册 - 完整授权流程
     * @param code 微信小程序登录接口返回的code
     * @param nickname 用户昵称
     * @param avatarUrl 用户头像URL
     * @return 登录/注册的用户信息
     */
    public Users wechatLogin(String code, String nickname, String avatarUrl) {
        // 通过code换取openid
        Map<String, String> openIdResult = getOpenIdByCode(code);
        if (openIdResult == null || !openIdResult.containsKey("openid")) {
            log.error("微信登录失败: 获取openid失败");
            throw new RuntimeException("微信登录失败：无法获取用户信息");
        }
        
        String openid = openIdResult.get("openid");
        // 可选：保存session_key用于后续业务逻辑
        String sessionKey = openIdResult.get("session_key");
        
        // 调用原有登录注册逻辑
        return loginOrRegister(openid, nickname, avatarUrl);
    }

    /**
     * 微信登录或注册（内部方法，由wechatLogin调用）
     * 新用户注册后不会自动加入团队，需要受邀请后加入
     */
    @Override
    @Transactional
    public Users loginOrRegister(String wxOpenid, String nickname, String avatarUrl) {
        Users user = this.lambdaQuery()
                .eq(Users::getWxOpenid, wxOpenid)
                .one();

        if (user == null) {
            // 检查是否存在被软删除的历史账号
            Users deletedUser = this.baseMapper.selectByOpenidIncludeDeleted(wxOpenid);
            if (deletedUser != null && deletedUser.getDeletedAt() == null) {
                // 说明在高并发下刚插入成功即可返回
                return deletedUser;
            }
            if (deletedUser != null) {
                log.info("发现软删除用户，恢复账号: userId={}, nickname={}", deletedUser.getId(), nickname);
                deletedUser.setDeletedAt(null);
                deletedUser.setNickname(nickname);
                deletedUser.setAvatarUrl(avatarUrl);
                deletedUser.setDirection(deletedUser.getDirection() == null ? "general" : deletedUser.getDirection());
                baseMapper.updateById(deletedUser);
                return deletedUser;
            }

            // 新用户注册
            user = new Users();
            user.setWxOpenid(wxOpenid);
            user.setNickname(nickname);
            user.setAvatarUrl(avatarUrl);
            user.setDirection("general"); // 默认方向为general
            baseMapper.insert(user); // 保存新用户

            log.info("新用户注册: userId={}, nickname={}", user.getId(), nickname);
        } else {
            // 老用户更新信息
            user.setNickname(nickname);
            if (avatarUrl != null) {
                user.setAvatarUrl(avatarUrl);
            }
            baseMapper.updateById(user); // 更新用户信息
            log.info("老用户登录更新信息: userId={}, nickname={}", user.getId(), nickname);
        }

        return user;
    }

    /**
     * 检查用户是否已加入团队
     */
    @Override
    public boolean isUserInTeam(Long userId) {
        LambdaQueryWrapper<TeamMember> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TeamMember::getUserId, userId)
                .eq(TeamMember::getTeamId, 1L); // 默认团队ID为1

        TeamMember teamMember = teamMemberMapper.selectOne(queryWrapper);
        return teamMember != null;
    }

    /**
     * 检查用户是否是管理员
     */
    @Override
    public boolean isAdmin(Long userId) {
        // 检查用户是否已加入团队
        if (!isUserInTeam(userId)) {
            log.debug("用户未加入团队，不是管理员: userId={}", userId);
            return false;
        }

        // 获取团队成员信息
        LambdaQueryWrapper<TeamMember> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TeamMember::getUserId, userId)
                .eq(TeamMember::getTeamId, 1L); // 默认团队ID为1

        TeamMember teamMember = teamMemberMapper.selectOne(queryWrapper);
        if (teamMember == null) {
            log.debug("未找到团队成员信息，不是管理员: userId={}", userId);
            return false;
        }

        // 检查角色ID是否为管理员角色（假设管理员角色ID为1）
        // 这里需要根据您的实际角色表设计来调整
        boolean isAdmin = teamMember.getRoleId() != null && teamMember.getRoleId() == 1L;

        if (isAdmin) {
            log.debug("用户是管理员: userId={}", userId);
        } else {
            log.debug("用户不是管理员: userId={}, roleId={}", userId, teamMember.getRoleId());
        }

        return isAdmin;
    }

    /**
     * 获取用户个人信息（包含团队信息）
     */
    @Override
    public UserProfile getProfileWithTeamInfo(Long userId) {
        Users user = baseMapper.selectById(userId);
        if (user == null) {
            return null;
        }

        UserProfile profile = new UserProfile();
        profile.setUser(user);
        profile.setInTeam(isUserInTeam(userId));

        if (profile.isInTeam()) {
            // 获取团队成员信息
            LambdaQueryWrapper<TeamMember> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(TeamMember::getUserId, userId)
                    .eq(TeamMember::getTeamId, 1L);

            TeamMember teamMember = teamMemberMapper.selectOne(queryWrapper);
            profile.setTeamMember(teamMember);
        }

        return profile;
    }

    /**
     * 获取用户个人信息
     */
    @Override
    public Users getProfile(Long userId) {
        return baseMapper.selectById(userId);
    }

    /**
     * 更新用户个人信息
     */
    @Override
    public boolean updateProfile(Users user) {
        int result = baseMapper.updateById(user);
        return result > 0;
    }

    /**
     * 设置用户专业方向
     */
    @Override
    @Transactional
    public boolean setDirection(Long userId, String direction) {
        // 先查询用户是否存在
        Users user = baseMapper.selectById(userId);
        if (user == null) {
            log.error("设置专业方向失败: 用户不存在, userId={}", userId);
            return false;
        }

        // 验证方向值是否有效
        String[] validDirections = {"frontend", "backend", "ui", "cv", "pm", "embedded", "general"};
        boolean isValid = false;
        for (String validDir : validDirections) {
            if (validDir.equals(direction)) {
                isValid = true;
                break;
            }
        }

        if (!isValid) {
            log.error("设置专业方向失败: 无效的方向值, userId={}, direction={}", userId, direction);
            return false;
        }

        // 设置新的专业方向
        user.setDirection(direction);
        int result = baseMapper.updateById(user);

        if (result > 0) {
            // 如果用户已加入团队，同时更新团队成员表中的方向信息
            if (isUserInTeam(userId)) {
                updateTeamMemberDirection(userId, direction);
            }
            log.info("用户专业方向设置成功: userId={}, direction={}", userId, direction);
        }

        return result > 0;
    }

    /**
     * 更新团队成员方向信息
     */
    private void updateTeamMemberDirection(Long userId, String direction) {
        LambdaQueryWrapper<TeamMember> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TeamMember::getUserId, userId)
                .eq(TeamMember::getTeamId, 1L); // 默认团队ID

        TeamMember teamMember = teamMemberMapper.selectOne(queryWrapper);
        if (teamMember != null) {
            teamMember.setDirection(direction);
            teamMemberMapper.updateById(teamMember);
            log.debug("更新团队成员方向信息: userId={}, direction={}", userId, direction);
        }
    }

    /**
     * 软删除用户（仅管理员可用）
     */
    @Override
    @Transactional
    public boolean softDeleteUser(Long userId, Long currentUserId) {
        // 先查询用户是否存在
        Users user = baseMapper.selectById(userId);
        if (user == null) {
            log.error("软删除用户失败: 用户不存在, userId={}", userId);
            return false;
        }

        // 不能删除自己
        if (userId.equals(currentUserId)) {
            log.error("软删除用户失败: 不能删除自己, userId={}", userId);
            return false;
        }

        // 执行软删除（逻辑删除）
        int result = baseMapper.deleteById(userId);

        if (result > 0) {
            // 同时从团队中移除用户
            removeUserFromTeam(userId);
            log.info("用户软删除成功: userId={}, deletedBy={}", userId, currentUserId);
        }

        return result > 0;
    }

    /**
     * 从团队中移除用户
     */
    private void removeUserFromTeam(Long userId) {
        LambdaQueryWrapper<TeamMember> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TeamMember::getUserId, userId)
                .eq(TeamMember::getTeamId, 1L); // 默认团队ID

        int deleteCount = teamMemberMapper.delete(queryWrapper);
        if (deleteCount > 0) {
            log.debug("从团队中移除用户: userId={}", userId);
        }
    }

    /**
     * 获取所有用户列表（仅管理员可用）
     */
    @Override
    public List<Users> getAllUsers() {
        // 构建查询条件：只查询未删除的用户
        LambdaQueryWrapper<Users> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.isNull(Users::getDeletedAt); // 软删除字段为null表示未删除

        return baseMapper.selectList(queryWrapper);
    }

    /**
     * 根据方向获取用户列表
     */
    @Override
    public List<Users> getUsersByDirection(String direction) {
        LambdaQueryWrapper<Users> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Users::getDirection, direction)
                .isNull(Users::getDeletedAt);

        return baseMapper.selectList(queryWrapper);
    }

    /**
     * 根据团队ID获取用户列表
     */
    @Override
    public List<Users> getUsersByTeamId(Long teamId) {
        // 通过团队成员表关联查询
        return baseMapper.selectUsersByTeamId(teamId);
    }

    /**
     * 根据角色获取用户列表
     */
    @Override
    public List<Users> getUsersByRole(String role) {
        // 通过团队成员表和角色表关联查询
        return baseMapper.selectUsersByRole(role);
    }

    /**
     * 统计用户数量
     */
    @Override
    public Long getUserCount() {
        LambdaQueryWrapper<Users> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.isNull(Users::getDeletedAt);

        return baseMapper.selectCount(queryWrapper);
    }

    /**
     * 根据方向统计用户数量
     */
    @Override
    public Long getUserCountByDirection(String direction) {
        LambdaQueryWrapper<Users> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Users::getDirection, direction)
                .isNull(Users::getDeletedAt);

        return baseMapper.selectCount(queryWrapper);
    }
}